﻿using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;

namespace CRM.Caches
{
    public abstract class BaseCache<TItem>
    {
        private readonly IMemoryCache _cache;

        protected BaseCache(IMemoryCache cache)
        {
            _cache = cache;
        }

        protected Task<T> GetOrCreateAsync<T>(string key, Func<ICacheEntry, Task<T>> factory)
        {
            var typeName = GetType().Name;
            return _cache.GetOrCreateAsync(GetName(typeName, key), factory);
        }

        /// <summary>
        /// 根据key获取对象
        /// </summary>
        /// <param name="key"></param>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        protected abstract Task<TItem> GetItem(object key, MyDbContext dbContext);
        
        public void FlushItem(object key)
        {
            var typeName = GetType().Name;
            var cacheKey = GetName(typeName, key.ToString());
            _cache.Remove(cacheKey);
        }

        public static string GetName(string cacheClass, string key)
        {
            return GetPrefix(cacheClass) + key;
        }
        public static string GetPrefix(string cacheClass)
        {
            return cacheClass.Replace("Cache", "") + '_';
        }
    }
}